<?php
declare (strict_types=1);

namespace app\common\queue\school;

use app\common\exception\LogicException;
use app\common\model\payment\PaymentOrderItem as POI;
use app\school\logic\school\School;
use app\school\logic\school\SchoolSplitConfig;
use app\school\model\school\SchoolLevel as SchoolLevelModel;

/**
 * 机构等级类
 */
class Level
{
    public function run()
    {
        // 20已付款30申请退款中70已支付但被管理员移除
        $data = app(POI::class)->alias('i')->field('i.mhm_id,sum(i.payment) as sum')->join('payment_order o', 'o.status IN (20,30,70) AND o.order_no=i.order_no')->group('i.mhm_id')->select();

        if (!$data->isEmpty()) {
            foreach ($data as $v) {
                // 机构比例
                $mhm_id = $v->mhm_id;
                if (1 == $mhm_id) return;
                // 机构独立分成配置
                $mhm_split_config = app(SchoolSplitConfig::class)->getSplitConfig($mhm_id);
                if ($mhm_split_config) return;
                // 机构等级
                $level_id = app(SchoolLevelModel::class)->where('min_sales_price', '<', $v->sum)->order('proportion', 'DESC')->value('id');
                if (!$level_id) return;
                //
                $school = app(School::class)->findOrEmpty($mhm_id);
                if ($school->level_id == $level_id) return;
                //
                $school->level_id = $level_id;
                if (!$school->save()) throw new LogicException("机构等级更新失败，机构ID为" . $mhm_id);
            }
        }
    }
}
